<template>
    <div>
        <transition name="el-zoom-in-top">
            <div class="menu tabmenu" v-if="showMenu" ref="rightMenu">
                <div class="menuItem" @click="menuClose('Self')">关闭</div>
                <div class="menuItem" @click="menuClose('Right')">关闭右侧菜单</div>
                <div class="menuItem" @click="menuClose('Left')">关闭左侧菜单</div>
                <div class="menuItem" @click="menuClose('Save')">关闭已保存</div>
                <div class="menuItem" @click="menuClose('Other')">全部其他</div>
                <div class="menuItem" @click="menuClose('All')">全部关闭</div>
            </div>
        </transition>
        <el-tabs class="main-box" :class="{'empty' : !tabs.length}" @tab-click="handleClick" v-model="tabsValue"
            type="card" editable @edit="tagEvent">
            <el-tab-pane :key="item.UUID" v-for="(item, index) in tabs" :name="item.UUID">
                <tabItem slot="label" :tabValue="item" @contextmenu.native.prevent="rightCLick($event,item.UUID)"
                    @click.native.middle="tagEvent(item.UUID, 'remove')"></tabItem>
                <contentBox :ref="'content-' + item.UUID" :contentValue="item"></contentBox>
            </el-tab-pane>
            <el-dialog title="警告" :visible.sync="dialogVisible" width="30%">
                <span v-if="closeTagCache.length != 1">部分接口尚未保存，是否关闭？</span>
                <span v-if="closeTagCache.length == 1">接口尚未保存，是否关闭？</span>
                <div slot="footer" class="dialog-footer" style="text-align: center;">
                    <el-button type="primary" v-if="closeTagCache.length !=1" @click="closeTag('save')">关闭已保存
                    </el-button>
                    <el-button type="primary" @click="closeTag('all')">关 闭</el-button>
                </div>
            </el-dialog>
        </el-tabs>

        <el-drawer title="自定义参数" size="380px" :visible.sync="showDrawer" :before-close="closeDrawer"
            :with-header="false">
            <Custom></Custom>
        </el-drawer>

        <el-dialog title="选择文件夹" append-to-body :class="theme" :visible.sync="showSaveFolder" width="600px">
            <savefolderList></savefolderList>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" size="samll" @click="saveToFolder">选择</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    const uuid = require('uuid');

    import contentBox from './content';
    import { mapState } from "vuex";
    import tabItem from './tab';
    import Custom from './custom';
    import savefolderList from '../saveFolderList'


    export default {
        components: {
            savefolderList,
            tabItem,
            contentBox,
            Custom,
        },
        data() {
            return {
                // showSaveFolder: false,
                showDrawer: false,
                showMenu: false,
                closeTagCache: [],
                dialogVisible: false,
                tabsValue: null,
                tabs: [],
                rightItemActive: null,
            }
        },
        watch: {
            activeId(newVal, oldVal) {
                this.activeTag(newVal);
            },
            CustomDrawer(newVal, oldVal) {
                this.showDrawer = newVal;
            },
        },
        computed: {
            showSaveFolder: {
                get() {
                    return this.$store.state.saveFolder.showSaveFolder
                },
                set(val) {
                    if (!val) {
                        this.$store.dispatch('saveFolder/clearFolderObject');
                    };
                    this.$store.state.saveFolder.showSaveFolder = val;
                },
            },
            ...mapState("theme", {
                theme: state => state.theme,
            }),
            ...mapState("Tree", {
                apiObject: state => state.apiObject,
            }),
            ...mapState("ApiActive", {
                activeId: state => state.activeId,
            }),
            ...mapState("customKey", {
                CustomDrawer: state => state.CustomDrawer,
            }),
        },
        destroyed() {
            document.removeEventListener('keydown', this.saveEvent);
        },
        mounted() {
            document.addEventListener('keydown', this.saveEvent);
        },
        methods: {
            saveEvent(e) {
                e = window.event || e;
                var keycode = e.keyCode || e.which;
                if (e.ctrlKey && keycode == 83) {
                    e.preventDefault();
                    if (this.tabs.length) {
                        this.$refs['content-' + this.tabsValue][0].optionSelect('Save');
                    };
                };
            },
            closeDrawer() {
                this.$store.dispatch('customKey/colseCustomDrawer');
            },
            menuClose(type) {
                if (type == 'Self') {
                    this.closeTagCache = [this.rightItemActive];
                    this.preClose();
                } else if (type == 'All') {
                    this.closeTagCache = [];
                    this.tabs.forEach(tab => {
                        this.closeTagCache.push(tab.UUID);
                    });
                    this.preClose();
                } else if (type == 'Save') {
                    this.closeTagCache = [];
                    this.tabs.forEach(tab => {
                        this.closeTagCache.push(tab.UUID);
                    });
                    this.preClose(true);
                } else if (type == 'Other') {
                    this.closeTagCache = [];
                    this.tabs.forEach(tab => {
                        if (tab.UUID != this.rightItemActive) {
                            this.closeTagCache.push(tab.UUID);
                        };
                    });
                    this.preClose();
                } else if (type == 'Left') {
                    this.closeTagCache = [];
                    this.tabs.forEach(tab => {
                        if (tab.UUID == this.rightItemActive) {
                            return false;
                        } else {
                            this.closeTagCache.push(tab.UUID);
                        };
                    });
                    this.preClose();
                } else if (type == 'Right') {
                    this.closeTagCache = [];
                    let Star = false;
                    for (let i = 0; i < this.tabs.length; i++) {
                        const tab = this.tabs[i];
                        if (Star) {
                            this.closeTagCache.push(tab.UUID);
                        } else if (tab.UUID == this.rightItemActive) {
                            Star = true;
                        };
                    };
                    this.preClose();
                };
            },
            rightCLick(event, UUID) {
                this.rightItemActive = UUID;
                this.showMenu = false;
                this.showMenu = true;
                this.$nextTick(() => {
                    this.$refs.rightMenu.style.top = event.clientY + 'px';
                    if (document.body.clientWidth - 155 < event.clientX) {
                        this.$refs.rightMenu.style.right = (document.body.clientWidth - event.clientX) + 'px';
                        this.$refs.rightMenu.style.left = 'auto';
                    } else {
                        this.$refs.rightMenu.style.right = 'auto';
                        this.$refs.rightMenu.style.left = event.clientX + 'px';
                    };
                    document.addEventListener('click', this.clearRightMenu);
                });
            },
            clearRightMenu() {
                this.showMenu = false;
                document.removeEventListener('click', this.clearRightMenu);
            },
            changeValue(UUID, type) {
                var name = 'tab-' + UUID;
                this.$refs[name][0].change(type);
            },
            handleClick(tab, event) {
                for (let i = 0; i < this.tabs.length; i++) {
                    const tabItem = this.tabs[i];
                    if (tab.name == tabItem.UUID && tabItem.oldValue.id) {
                        this.$store.dispatch('ApiActive/setActiveId', tabItem.oldValue.id)
                        break;
                    };
                };
            },
            isInTagList(id) {
                let isHave = false;
                for (let i = 0; i < this.tabs.length; i++) {
                    const tab = this.tabs[i];
                    if (tab.oldValue.id == id) {
                        isHave = tab;
                        break;
                    };
                };
                return isHave;
            },
            activeTag(id) {
                if (this.apiObject.hasOwnProperty(id)) {
                    let tagItem = this.isInTagList(id);
                    if (tagItem) {
                        this.tabsValue = tagItem.UUID;
                    } else {
                        this.addTag(this.apiObject[id], false);
                    }
                };
            },
            addTag(apiObject, isNew) {
                let objectValue = {
                    UUID: uuid.v1(),
                    id: apiObject.id || !isNew,
                    isChange: isNew,
                    newValue: JSON.parse(JSON.stringify(apiObject)),
                    oldValue: apiObject
                };
                this.tabs.push(objectValue);
                this.tabsValue = objectValue.UUID;
            },
            removeTag(targetName) {
                let tabs = this.tabs;
                let activeName = this.tabsValue;
                if (activeName === targetName) {
                    tabs.forEach((tab, index) => {
                        if (tab.UUID === targetName) {
                            let nextTab = tabs[index + 1] || tabs[index - 1];
                            if (nextTab) {
                                activeName = nextTab.UUID;
                            }
                        }
                    });
                }
                this.tabs = tabs.filter(tab => tab.UUID !== targetName);
                this.tabsValue = activeName;

                if (this.tabs.length == 0) {
                    this.$store.dispatch('ApiActive/setActiveId', null);
                    this.tabsValue = null;
                } else {
                    tabs.forEach((tab, index) => {
                        if (tab.UUID == activeName) {
                            this.$store.dispatch('ApiActive/setActiveId', tab.oldValue.id)
                            return false;
                        }
                    });
                };
            },
            closeTag(action) {
                if (action == 'save') {
                    var cacheArray = [];
                    this.closeTagCache.forEach(UUID => {
                        if (!this.checkIsChange(UUID)) {
                            this.removeTag(UUID);
                        };
                    });
                } else if (action == 'all') {
                    this.closeTagCache.forEach((tab, index) => {
                        this.removeTag(tab);
                    });
                };
                this.dialogVisible = false;
                setTimeout(() => {
                    this.closeTagCache = [];
                }, 300);
            },
            checkIsChange(UUID) {
                let isChange = false;
                this.tabs.forEach((tab, index) => {
                    if (UUID == tab.UUID) {
                        isChange = tab.isChange
                    };
                    return false;
                });
                return isChange;
            },
            preClose(ignore) {
                let isChangeArray = [];
                this.closeTagCache.forEach(UUID => {
                    if (this.checkIsChange(UUID)) {
                        isChangeArray.push(UUID);
                    } else {
                        this.removeTag(UUID);
                    };
                });
                if (ignore) {
                    this.closeTagCache = [];
                    return;
                } else if (isChangeArray.length != 0) {
                    this.closeTagCache = isChangeArray;
                    this.dialogVisible = true;
                } else {
                    this.closeTagCache = [];
                };
            },
            tagEvent(targetName, action) {
                if (action === 'add') {
                    this.addTag({
                        title: 'new File',
                        type: 'get',
                        typeStr: 'GET',
                        description: '',
                        url: '',
                        status: 0,
                        header: '{}',
                        body: '',
                        fromdata: '',
                        query: '',
                        rest: '',
                        before: '',
                        after: '',
                    }, true);
                };
                if (action === 'remove') {
                    this.closeTagCache = [targetName];
                    this.preClose();
                };
            },
            saveToFolder() {
                this.$store.dispatch('saveFolder/saveFolderObject');
                this.$store.dispatch('saveFolder/clearFolderObject');
            },
        }
    }

</script>

<style scoped>
    .main-box.el-tabs {
        position: absolute;
        top: 0px;
        width: 100%;
        bottom: 0;
    }
</style>